<?php

namespace Haozing\FastCore\Command;

use Hyperf\Command\Annotation\Command;
use Symfony\Component\Console\Input\InputOption;
use Throwable;

#[Command]
class UninstallCommand extends CoreCommand
{
    protected ?string $name = 'hei:uninstall';
    public function configure(): void
    {
        parent::configure();
        $this->setHelp('run "php bin/hyperf.php hei:create" create the new plugin');
        $this->setDescription('heiAdmin system gen plugin command');
        //设置是否清楚目录选项
        $this->addOption('clear', 'c', InputOption::VALUE_NONE, '是否清除目录');
    }

    /**
     * @throws Throwable
     */
    public function handle(): void
    {
        //通过询问用户，是否开始拆卸，来拆卸模块
        $this->output->writeLn($this->getGreenText('Start uninstalling plugin...'));
        $isUn = $this->ask('Are you sure you want to uninstall the plugin?[y/n]', 'n');
        if ($isUn == 'y') {
            // 读取composer.json。获取所有安装的插件
            $composerJson = json_decode(file_get_contents(BASE_PATH . '/composer.json'), true);
            $require = $composerJson['require'];
            $require = array_keys($require);
            $require = array_filter($require, function ($item) {
                return (strpos($item, 'plugins/') !== false) || (strpos($item, 'apps/') !== false);
            });
            $require = array_values($require);
            //将模型列表编号显示
            $this->output->writeLn($this->getGreenText('Please select the plugin you want to uninstall'));
            for ($i = 0; $i < count($require); $i++) {
                $this->output->writeLn($this->getGreenText($i . ':' . $require[$i]));
            }
            $select = $this->ask('Please enter the number of the plugin you want to uninstall', '0');

            $selectModule = '';
            if (is_numeric($select) && $select >= 0 && $select < count($require)) {
                //todo 获取需要拆卸的插件，获取插件的详细信息
                $selectModule = $require[$select];
                $this->output->writeLn($this->getGreenText('Start uninstalling plugin...'));
                $se = shell_exec('composer remove ' . $selectModule);
                //输出结果
                $this->output->writeLn($this->getGreenText($se));
            }

            //判断是否有清楚目录选项
            if ($this->input->getOption('clear') && !empty($selectModule)) {
                $this->output->writeLn($this->getGreenText('Start cleaning plugin directory...'.BASE_PATH .DIRECTORY_SEPARATOR. $this->getComponentUrl($selectModule)));
                $this->output->writeLn($this->getGreenText(shell_exec('rm -rf ' . BASE_PATH .DIRECTORY_SEPARATOR. $this->getComponentUrl($selectModule))));
            }

        }
    }

    /**
     * 将组件字符串转为地址
     */
    public function getComponentUrl(string $component): string
    {
        //app/shop.user和plugin/shop 两种组件格式,将/和.转化为DIRECTORY_SEPARATOR
        return str_replace(['/', '.'], DIRECTORY_SEPARATOR, $component);
    }
}